package com.ywb.config;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ywb.utils.JWTUtils;
import com.ywb.utils.R;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取请求中的cookie值,依次遍历
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
//                找到名称为token的cookie
                if(cookie.getName().equals("token")){
//                    获取token的值
                    String token = cookie.getValue();
                    try{
//                        使用JWTUtils验证token合法性
                        DecodedJWT verify = JWTUtils.verify(token);
//                        获取token中的userName和id作为返回到页面中
                        String userName = verify.getClaim("username").asString();
//                        注意这里的调用的asString,而不是toString()
                        request.setAttribute("userName", verify.getClaim("username").asString());
                        request.setAttribute("id", verify.getClaim("id").asString());

                        return true;
//                        验证失败,根据抛出的异常返回提示信息
                    }catch (TokenExpiredException e){
                        e.printStackTrace();
                        request.setAttribute("resultInfo",R.error().message("token已过期,请重新登录"));
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute("resultInfo",R.error().message("token验证失败,请重新登录"));
                    }
                }
            }

            if(request.getAttribute("resultInfo") == null)
                request.setAttribute("resultInfo", R.error().message("没有权限,请先登录"));
//            拦截所有token验证失败的请求,并跳转到登录页面进行登录
            request.getRequestDispatcher("/user/login.jsp").forward(request, response);
            return false;
        }

//        判断sessioin中是否有UserController登录成功存入的user,如果没有就拦截，返回登录页面
        if(request.getSession().getAttribute("user") == null){
            request.setAttribute("resultInfo", R.error().message("没有权限请先登录"));
            request.getRequestDispatcher("/user/login.jsp").forward(request, response);
            return false;
        }
        return true;
    }
}
